<template>
  <div class="approval-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="产品名称" prop="name">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入产品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待审批" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="产品名称" min-width="150" />
        <el-table-column prop="type" label="产品类型" width="120">
          <template #default="scope">
            <el-tag :type="getProductTypeTag(scope.row.type)">
              {{ getProductTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="所属分类" width="120" />
        <el-table-column prop="submitter" label="申请人" width="120" />
        <el-table-column prop="submitTime" label="申请时间" width="180" />
        <el-table-column prop="status" label="审批状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approver" label="审批人" width="120" />
        <el-table-column prop="approvalTime" label="审批时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                link
                type="primary"
                @click="handleView(scope.row)"
              >查看</el-button>
              <template v-if="scope.row.status === 'pending'">
                <el-button
                  link
                  type="success"
                  @click="handleApprove(scope.row, 'approved')"
                >通过</el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleApprove(scope.row, 'rejected')"
                >拒绝</el-button>
              </template>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审批弹窗 -->
    <el-dialog
      v-model="approveDialogVisible"
      :title="approveAction === 'approved' ? '审批通过' : '审批拒绝'"
      width="500px"
    >
      <el-form
        :model="approveForm"
        :rules="approveFormRules"
        ref="approveFormRef"
        label-width="100px"
      >
        <el-form-item label="产品名称">
          <div>{{ currentProduct.name }}</div>
        </el-form-item>
        <el-form-item label="申请人">
          <div>{{ currentProduct.submitter }}</div>
        </el-form-item>
        <el-form-item label="申请时间">
          <div>{{ currentProduct.submitTime }}</div>
        </el-form-item>
        <el-form-item label="审批意见" prop="approvalOpinion">
          <el-input
            v-model="approveForm.approvalOpinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button 
            :type="approveAction === 'approved' ? 'success' : 'danger'"
            @click="submitApprove"
            :loading="submitLoading"
          >确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="审批详情"
      width="700px"
    >
      <div v-loading="detailLoading" style="min-height: 200px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="产品名称">{{ approvalDetail.name || '--' }}</el-descriptions-item>
          <el-descriptions-item label="产品类型">
            <template v-if="approvalDetail.type">
              <el-tag :type="getProductTypeTag(approvalDetail.type)">
                {{ getProductTypeName(approvalDetail.type) }}
              </el-tag>
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="所属分类">{{ approvalDetail.categoryName || '--' }}</el-descriptions-item>
          <el-descriptions-item label="审批状态">
            <template v-if="approvalDetail.status">
              <el-tag :type="getStatusTag(approvalDetail.status)">
                {{ getStatusName(approvalDetail.status) }}
              </el-tag>
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">{{ approvalDetail.submitter || '--' }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ approvalDetail.submitTime || '--' }}</el-descriptions-item>
          <el-descriptions-item label="审批人" v-if="approvalDetail.status !== 'pending'">
            {{ approvalDetail.approver || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="审批时间" v-if="approvalDetail.status !== 'pending'">
            {{ approvalDetail.approvalTime || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="审批意见" :span="2" v-if="approvalDetail.status !== 'pending'">
            {{ approvalDetail.approvalOpinion || '--' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="center">产品信息</el-divider>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="贷款金额">
            <template v-if="approvalDetail.loanAmount && approvalDetail.loanAmount.min !== undefined">
              {{ approvalDetail.loanAmount.min }}-{{ approvalDetail.loanAmount.max }}万
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="贷款期限">
            <template v-if="approvalDetail.loanTerm && approvalDetail.loanTerm.min !== undefined">
              {{ approvalDetail.loanTerm.min }}-{{ approvalDetail.loanTerm.max }}个月
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="年化利率">{{ approvalDetail.interestRate ? `${approvalDetail.interestRate}%` : '--' }}</el-descriptions-item>
          <el-descriptions-item label="还款方式">{{ approvalDetail.repaymentMethod ? getRepaymentMethodName(approvalDetail.repaymentMethod) : '--' }}</el-descriptions-item>
          <el-descriptions-item label="申请条件" :span="2">{{ approvalDetail.applyCondition || '--' }}</el-descriptions-item>
          <el-descriptions-item label="所需材料" :span="2">{{ approvalDetail.requiredMaterials || '--' }}</el-descriptions-item>
          <el-descriptions-item label="产品说明" :span="2">{{ approvalDetail.description || '--' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 添加产品特性显示 -->
        <template v-if="approvalDetail.features && approvalDetail.features.length > 0">
          <el-divider content-position="center">产品特性</el-divider>
          <el-card v-for="(feature, index) in approvalDetail.features" :key="index" class="feature-card">
            <div class="feature-header">{{ feature.name }}</div>
            <div class="feature-content">{{ feature.value }}</div>
          </el-card>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { approvalApi } from '@/api/product'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const total = ref(0)
const tableData = ref([])

// 审批表单
const approveDialogVisible = ref(false)
const approveFormRef = ref(null)
const approveAction = ref('approved') // approved 或 rejected
const submitLoading = ref(false)
const currentProduct = ref({})
const approveForm = reactive({
  id: '',
  status: '',
  approvalOpinion: ''
})

// 详情数据
const detailVisible = ref(false)
const detailLoading = ref(false)
const approvalDetail = ref({})

// 审批表单校验规则
const approveFormRules = {
  approvalOpinion: [
    { required: true, message: '请输入审批意见', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 产品类型标签
const getProductTypeTag = (type) => {
  const map = {
    personal: '',
    business: 'success',
    consumer: 'warning',
    mortgage: 'danger'
  }
  return map[type] || 'info'
}

// 产品类型名称
const getProductTypeName = (type) => {
  const map = {
    personal: '个人贷款',
    business: '企业贷款',
    consumer: '消费贷款',
    mortgage: '抵押贷款'
  }
  return map[type] || type
}

// 还款方式名称
const getRepaymentMethodName = (method) => {
  const map = {
    equal_principal_interest: '等额本息',
    equal_principal: '等额本金',
    interest_only: '到期还本付息',
    monthly_interest: '按月付息到期还本'
  }
  return map[method] || method
}

// 审批状态标签
const getStatusTag = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

// 审批状态名称
const getStatusName = (status) => {
  const map = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return map[status] || status
}

// 获取审批列表
const getApprovalList = async () => {
  loading.value = true
  try {
    const res = await approvalApi.getList(searchForm)
    console.log('审批列表接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理嵌套数据结构
      let approvalData = null
      let totalCount = 0
      
      // 检查不同层级的嵌套结构
      if (res.data && res.data.rows) {
        approvalData = res.data.rows
        totalCount = res.data.total
      } else if (res.data && res.data.data && res.data.data.rows) {
        approvalData = res.data.data.rows
        totalCount = res.data.data.total
      } else if (res.data && (res.data.code === 200 || res.data.code === '200') && res.data.data && res.data.data.rows) {
        // 处理嵌套返回格式: {code:200, msg:"", data:{code:200, msg:"", data:{rows:[...], total:10}}}
        approvalData = res.data.data.rows
        totalCount = res.data.data.total
      } else {
        console.warn('审批列表返回格式不符合预期', res)
        approvalData = []
        totalCount = 0
      }
      
      console.log('处理后的审批数据:', approvalData)
      
      tableData.value = approvalData
      total.value = totalCount
    } else {
      ElMessage.error(res.msg || '获取审批列表失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取审批列表出错', error)
    ElMessage.error('获取审批列表出错: ' + (error.message || '未知错误'))
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  searchForm.pageNum = 1
  getApprovalList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  getApprovalList()
}

const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  getApprovalList()
}

// 查看详情
const handleView = async (row) => {
  try {
    detailVisible.value = true
    detailLoading.value = true
    
    // 先显示基本信息
    approvalDetail.value = { ...row }
    
    // 获取完整详情
    const res = await approvalApi.getDetail(row.id)
    console.log('审批详情接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理嵌套数据结构 - 按层级依次尝试提取数据
      let detailData = null
      
      if (res.data && typeof res.data === 'object') {
        if (res.data.data && typeof res.data.data === 'object') {
          // 处理 {code: 200, data: {code: 200, data: {...}}} 结构
          if (res.data.data.data && typeof res.data.data.data === 'object') {
            detailData = res.data.data.data;
          } else {
            detailData = res.data.data;
          }
        } else {
          detailData = res.data;
        }
      }
      
      // 处理新的嵌套结构 {code:"200", msg:"操作成功", data:{code:200, msg:"操作成功", data:{...}}}
      if (res.data && (res.data.code === 200 || res.data.code === '200') && res.data.data && typeof res.data.data === 'object') {
        detailData = res.data.data;
      }
      
      if (detailData) {
        console.log('处理后的审批详情:', detailData)
        
        // 确保loanAmount和loanTerm字段格式正确
        if (detailData.loanAmount && typeof detailData.loanAmount === 'string') {
          try {
            detailData.loanAmount = JSON.parse(detailData.loanAmount);
          } catch (e) {
            console.warn('解析loanAmount失败:', e);
          }
        }
        
        if (detailData.loanTerm && typeof detailData.loanTerm === 'string') {
          try {
            detailData.loanTerm = JSON.parse(detailData.loanTerm);
          } catch (e) {
            console.warn('解析loanTerm失败:', e);
          }
        }
        
        // 确保features是数组
        if (detailData.features && typeof detailData.features === 'string') {
          try {
            detailData.features = JSON.parse(detailData.features);
          } catch (e) {
            console.warn('解析features失败:', e);
            detailData.features = [];
          }
        }
        
        approvalDetail.value = detailData
      } else {
        console.warn('审批详情返回格式不符合预期', res)
        ElMessage.warning('获取详情格式异常')
      }
    } else {
      ElMessage.error(res.msg || '获取审批详情失败')
    }
  } catch (error) {
    console.error('获取审批详情出错', error)
    ElMessage.error('获取审批详情出错: ' + (error.message || '未知错误'))
  } finally {
    detailLoading.value = false
  }
}

// 审批操作
const handleApprove = (row, action) => {
  currentProduct.value = row
  approveAction.value = action
  approveForm.id = row.id
  approveForm.status = action
  approveForm.approvalOpinion = ''
  approveDialogVisible.value = true
}

// 提交审批
const submitApprove = async () => {
  if (!approveFormRef.value) return
  await approveFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 准备提交数据
        const submitData = {
          id: approveForm.id,
          status: approveForm.status,
          approvalOpinion: approveForm.approvalOpinion
        }
        
        console.log('提交审批数据:', submitData) // 调试日志
        const res = await approvalApi.approveProduct(submitData)
        console.log('审批提交返回:', res) // 调试日志
        
        if (res.code === 200 || res.code === '200') {
          ElMessage.success(approveAction.value === 'approved' ? '审批通过成功' : '审批拒绝成功')
          approveDialogVisible.value = false
          getApprovalList()
        } else {
          ElMessage.error(res.msg || '审批操作失败')
        }
      } catch (error) {
        console.error('审批操作出错', error)
        ElMessage.error('审批操作出错: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    } else {
      console.log('表单校验失败', fields)
    }
  })
}

// 初始化
onMounted(() => {
  console.log('审批管理组件初始化')
  
  try {
    getApprovalList()
  } catch (error) {
    console.error('初始化审批列表失败:', error)
    ElMessage.error('加载审批数据失败，请稍后刷新页面')
  }
})
</script>

<style scoped>
.approval-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.feature-card {
  margin-bottom: 10px;
}

.feature-header {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
  color: #409EFF;
}

.feature-content {
  color: #606266;
}
</style> 